package com.sunplus.system.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunplus.common.constant.HttpStatus;
import com.sunplus.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.sunplus.common.annotation.Log;
import com.sunplus.common.constant.UserConstants;
import com.sunplus.common.core.controller.BaseController;
import com.sunplus.common.core.domain.AjaxResult;
import com.sunplus.common.core.domain.entity.SysRole;
import com.sunplus.common.core.domain.entity.SysUser;
import com.sunplus.common.core.domain.model.LoginUser;
import com.sunplus.common.enums.BusinessType;
import com.sunplus.common.utils.SecurityUtils;
import com.sunplus.common.utils.ServletUtils;
import com.sunplus.common.utils.StringUtils;
import com.sunplus.common.utils.poi.ExcelUtil;
import com.sunplus.framework.web.service.TokenService;
import com.sunplus.system.service.ISysPostService;
import com.sunplus.system.service.ISysRoleService;
import com.sunplus.system.service.ISysUserService;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/admin/userMgr")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysMenuService menuService;
    /**
     * 获取用户列表
     */
    @PostMapping("/listPain")
    public AjaxResult list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        JSONObject data = getDataTable(list);
        data.put("ButtonRight", "add,edit,del,view,SetRole,updatepassword");
        return AjaxResult.success(data);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 导入数据
     *
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId) {
        AjaxResult ajax = AjaxResult.success();
        List<Map> roles = roleService.selectRoleAll();
//      ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("roles", roles);
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/Add")
    public AjaxResult add(@Validated SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserIDUnique(user.getUserID()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，用户名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setGroupID(SecurityUtils.getLoginUser().getUser().getGroupID());
        user.setCreateUser(SecurityUtils.getLoginUser().getUser().getPID());
        user.setPassWord(SecurityUtils.encryptPassword(StringUtils.isEmpty(user.getPassWord()) ? user.getUserID() : user.getPassWord()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult edit(@Validated SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateUser(SecurityUtils.getLoginUser().getUser().getPID());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/BatchDelete")
    public AjaxResult remove(@RequestParam String[] ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassWord(SecurityUtils.encryptPassword(user.getPassWord()));
        user.setUpdateUser(SecurityUtils.getLoginUser().getUser().getPID());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 重置密码
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/UpdatePassWord")
    public AjaxResult updatePassWord(@RequestParam String[] userpids) {
        for (String ids : userpids) {
            SysUser user = new SysUser();
            user.setPID(ids);
            user.setPassWord("110509");
            user.setPassWord(SecurityUtils.encryptPassword(user.getPassWord()));
            user.setUpdateUser(SecurityUtils.getLoginUser().getUser().getPID());
            userService.resetPwd(user);
        }
        return AjaxResult.success();
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateUser(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 获取用户按钮  其实是有问题的
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/GetButtonRight")
    public AjaxResult getButtonRight() throws Exception {

        //menuService.


        return AjaxResult.success((Object) "<button class=\"layui-btn layuiadmin-btn-list\" data-type=\"add\">添加</button><button class=\"layui-btn layuiadmin-btn-list\" data-type=\"del\">删除</button><button class=\"layui-btn layuiadmin-btn-list\" data-type=\"updatepassword\">重置密码</button>");
    }


    @PostMapping("/customerQuery")
    public AjaxResult customerQuery() {
        String GroupId = SecurityUtils.getLoginUser().getUser().getGroupID();
        userService.customerQuery(GroupId);
        return AjaxResult.success("");
    }


    @PostMapping("/GetUserRight")
    public AjaxResult getUserRight() throws Exception {
        JSONObject user = new JSONObject();
        user.put("CustomerRight", 0);
        return AjaxResult.success(user);
    }

}
